package cn.ztydata.teachingsystem.heaven.web.filter;

import cn.ztydata.teachingsystem.heaven.web.wrapper.CustomSession;
import cn.ztydata.teachingsystem.heaven.web.wrapper.HttpSessionProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

/**
 * 认证过滤器
 */
public class AuthFilter implements Filter {

    private final static Logger log = LoggerFactory.getLogger(AuthFilter.class);

    @Autowired
    private CustomSession customHttpSession;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(final ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException {

        String excludePathes = request.getServletContext().getInitParameter("excludePathes");

        HttpServletRequest hrequest = (HttpServletRequest)request;

        String[] paths = excludePathes.split(";");

        if (this.isContains(hrequest.getRequestURI(), paths)) {// 只对指定过滤参数后缀进行过滤
            chain.doFilter(request, response);
            return;
        }

        final HttpSession sessionProxy = new HttpSessionProxy(customHttpSession);
        customHttpSession.setServletContext(request.getServletContext());
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(hrequest){

            @Override
            public HttpSession getSession(){
                return sessionProxy;
            }

            @Override
            public HttpSession getSession(boolean create){
                return sessionProxy;
            }
        };

        chain.doFilter(wrapper, response);

        //将会话数据回写入持久层
        customHttpSession.save();
    }

    public static boolean isContains(String container, String[] regx) {
        boolean result = false;

        for (int i = 0; i < regx.length; i++) {
            if (container.indexOf(regx[i]) != -1) {
                return true;
            }
        }
        return result;
    }

    @Override
    public void destroy(){
    }
}
